package com.zzf.concurrent.example.design.pattern.observer.thread.example;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author GaoFeng2017
 * @date 2019/9/6 10:53
 */
public abstract class AbstractRunnableObserver implements Runnable {

    private ThreadListener threadListener;

    public AbstractRunnableObserver(ThreadListener threadListener) {
        this.init(threadListener);
    }

    private void init(ThreadListener threadListener) {
        if (threadListener == null) {
            throw new NullPointerException();
        }
        this.threadListener = threadListener;
    }

    public void updateStatus(Thread thread,ThreadStatus status, Throwable cause) {
        RunnableObserverEvent event = new RunnableObserverEvent(thread, cause, status);
        threadListener.handle(event);
    }

    public enum ThreadStatus {
        /**
         * 运行中
         */
        RUNNING,
        /**
         * 发生异常
         */
        ERROR,
        /** 已终止 */
        TERMINATED,
        ;
    }

    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    public static class RunnableObserverEvent {
        private Thread target;
        private Throwable cause;
        private ThreadStatus threadStatus;
    }
}
